<!--
 * @Author: wei_jt@ecidi.com
 * @Date: 2019-07-22 11:04:00
 * @LastEditors: wei_jt@ecidi.com
 * @LastEditTime: 2021-12-30 16:23:29
 * @Description: 菜单详情
 -->
<template>
  <fks-dialog
    :visible.sync="show"
    :append-to-body="true"
    width="960px"
    :title="title"
    destroy-on-close
    @close="close"
  >
    <div slot="title">
      <i v-if="form.operate == 'add'" class="fks-icon-plus" />
      <i v-if="form.operate == 'edit'" class="fks-icon-edit" />
      <i v-if="form.operate == 'view'" class="fks-icon-view" />
      {{ title }}
    </div>
    <div class="main">
      <fks-form ref="form" label-width="100px" :model="form">
        <fks-form-item
          :span="12"
          lead
          :label="LANG.MENU_NAME"
          required
          prop="title"
        >
          <span slot="label">
            <span class="span-box">
              <span>{{ LANG.MENU_NAME }}</span>
              <fks-tooltip placement="top-start">
                <div
                  slot="content"
                  style="font-size: 14px; line-height: 20px"
                  class="tips-container"
                >
                  {{ LANG.MENU_NOTE }}
                </div>
                <i class="fks-icon-question" />
              </fks-tooltip>
            </span>
          </span>
          <fks-input
            v-model="form.title"
            :placeholder="LANG.ROUTE_TITLE"
            maxlength="50"
            show-word-limit
          />
        </fks-form-item>
        <fks-form-item :span="12" :label="LANG.ROUTE_JUMP" prop="type">
          <fks-radio-group v-model="type" size="medium" @change="change">
            <fks-radio-button
              v-for="route in routeTypes"
              :key="route.code"
              :label="route.code"
            >
              {{ route[$lang] }}
            </fks-radio-button>
          </fks-radio-group>
        </fks-form-item>

        <fks-form-item :span="12" lead :label="LANG.CODE" required prop="code">
          <fks-input
            v-model="form.code"
            :placeholder="LANG.ROUTE_NAME"
            maxlength="50"
            show-word-limit
          />
          <!-- <fks-input v-model="baseCode"></fks-input> -->
        </fks-form-item>
        <fks-form-item :span="12" :label="LANG.PARENT" prop="pathId">
          <menu-select
            :id="form.id"
            :path-id.sync="form.pathId"
            :parent-id.sync="form.parentId"
            :operate.sync="form.operate"
          />
        </fks-form-item>
        <fks-form-item :span="12" :label="LANG.ICON" prop="icon">
          <!-- 选择图标 -->
          <fks-input
            v-model="form.icon"
            class="icon-input"
            :placeholder="LANG.SELECT_HOLDER"
            style="cursor: pointer"
            :suffix-icon="
              iconSelShow ? 'fks-icon-arrow-up' : 'fks-icon-arrow-down'
            "
            maxlength="50"
            clearable
            @focus="iconSelShow = true"
            @clear="clear"
          >
            <template slot="prepend">
              <fks-icon v-if="form.icon" :icon-class="form.icon" />
            </template>
          </fks-input>
        </fks-form-item>

        <fks-form-item :span="12" :label="LANG.SORT" prop="sort">
          <fks-input
            v-model.number="form.sort"
            :placeholder="LANG.MENU_SORT"
            maxlength="50"
            oninput="value=value.replace(/[^0-9.]/g,'')"
          />
        </fks-form-item>
        <fks-form-item :span="12" lead :label="LANG.ACTIVATE" prop="enable">
          <fks-switch v-model="form.enable" />
        </fks-form-item>
        <fks-form-item :span="12" :label="LANG.IS_AUTH" prop="isAuth">
          <fks-switch v-model="form.isAuth" />
        </fks-form-item>
        <fks-form-item
          v-if="type == 'route'"
          :span="24"
          :label="LANG.COMPONENT"
          required
          prop="component"
        >
          <Path-select
            :id="form.id"
            :component.sync="form.component"
            :placeholder="LANG.SELECT_HOLDER"
          />
        </fks-form-item>
        <fks-form-item
          v-if="type == 'route'"
          :span="24"
          :label="LANG.PATH"
          prop="path"
          required
        >
          <fks-input
            v-model="form.path"
            :placeholder="LANG.ROUTE_PATH"
            maxlength="255"
            show-word-limit
          />
        </fks-form-item>
        <fks-form-item
          v-else
          :span="24"
          required
          :label="LANG.LINK_PATH"
          prop="path"
        >
          <fks-input
            v-model="form.path"
            :placeholder="LANG.LINK_PATH_TIPS"
            maxlength="255"
            show-word-limit
          />
        </fks-form-item>
        <fks-form-item :label="LANG.REMARK" prop="remark">
          <fks-input
            v-model="form.remark"
            type="textarea"
            maxlength="255"
            show-word-limit
          />
        </fks-form-item>
        <template v-if="showed">
          <fks-form-item
            :span="24"
            :label="LANG.HIGHLIGHT_MENU"
            prop="activeMenu"
          >
            <span slot="label">
              <span class="span-box">
                <span>{{ LANG.HIGHLIGHT_MENU }}</span>
                <fks-tooltip placement="top-start">
                  <div
                    slot="content"
                    style="font-size: 14px; line-height: 20px"
                    class="tips-container"
                  >
                    {{ LANG.MENUS_NOTE }}
                  </div>
                  <i class="fks-icon-question" />
                </fks-tooltip>
              </span>
            </span>
            <route-select
              :redirect.sync="activeMenu"
              :placeholder="LANG.SELECT_HOLDER"
            />
          </fks-form-item>
          <fks-form-item
            v-if="type == 'route'"
            :span="24"
            :label="LANG.REDIRECT"
            prop="redirect"
          >
            <route-select
              :redirect.sync="form.redirect"
              :placeholder="LANG.SELECT_HOLDER"
            />
          </fks-form-item>
          <fks-form-item :span="24" :label="LANG.DEFAULT_CONFIG">
            <span slot="label">
              <span class="span-box">
                <span>{{ LANG.DEFAULT_CONFIG }}</span>
                <fks-tooltip placement="top-start">
                  <div
                    slot="content"
                    style="font-size: 14px; line-height: 20px"
                    class="tips-container"
                  >
                    {{ LANG.META_NOTE }}
                  </div>
                  <i class="fks-icon-question" />
                </fks-tooltip>
              </span>
            </span>
            <fks-select
              v-model="config"
              style="width: 100%"
              multiple
              :placeholder="LANG.DEFAULT_CONFIG_TIPS"
            >
              <fks-option
                v-for="item in metaConfig"
                :key="item.code"
                :value="item.code"
                :label="item[$lang]"
              >
                <span>{{ item[$lang] }}</span>
              </fks-option>
            </fks-select>
          </fks-form-item>
          <fks-form-item
            v-if="type == 'route'"
            :span="24"
            :label="LANG.SELF_CONFIG"
          >
            <span slot="label">
              <span class="span-box">
                <span>{{ LANG.SELF_CONFIG }}</span>
                <fks-tooltip placement="top-start">
                  <div
                    slot="content"
                    style="font-size: 14px; line-height: 20px"
                    class="tips-container"
                    v-html="LANG.PARAMS_TYPE_TIPS"
                  />
                  <i class="fks-icon-question" />
                </fks-tooltip>
              </span>
            </span>
            <div class="meta-add">
              <fks-radio-group
                v-model="paramsType"
                clearable
                size="small"
                @change="changeType"
                @clear="clearType"
              >
                <fks-radio-button
                  v-for="item in paramsTypes"
                  :key="item.value"
                  :label="item.value"
                  :value="item.value"
                  :disabled="item.disabled"
                />
              </fks-radio-group>

              <fks-input
                :placeholder="LANG.PARAMS_NAME"
                v-model="key"
                maxlength="20"
              />

              <fks-input
                :placeholder="LANG.PARAMS_VALUE"
                v-model="value"
                maxlength="50"
              />

              <fks-button
                type="primary"
                size="small"
                :disabled="!key"
                @click="doneParams"
              >
                {{ LANG.ADD }}
              </fks-button>
            </div>
            <div v-if="showTag.length" class="meta-config">
              <fks-tag
                v-for="tag in showTag"
                :key="tag.key"
                :type="tag.type"
                closable
                class="meta-tag"
                @close="handleClose(tag)"
              >
                {{ tag.value }}
              </fks-tag>
            </div>
          </fks-form-item>
        </template>
        <fks-form-item :sapn="24" label>
          <fks-button
            label
            style="width: 100%"
            :icon="`fks-icon-arrow-${showed ? 'up' : 'down'}`"
            @click="showconfig()"
          >
            {{ showed ? LANG.HIDDEN_SETTING : LANG.MOST_SETTING }}
          </fks-button>
        </fks-form-item>
      </fks-form>
    </div>
    <!-- 图标选择弹窗 -->
    <icon-select
      :icon-sel-show="iconSelShow"
      @closeSelect="closeSelect"
      @saveSelect="saveSelect"
    />
    <template slot="footer" style="text-align: right">
      <fks-button
        type="primary"
        icon="fks-icon-check"
        :loading="loading"
        @click="submit"
      >
        {{ LANG.SAVE }}
      </fks-button>
    </template>
  </fks-dialog>
</template>
<script>
import * as Auth from '../api'
import { ENUM } from '@/store/State/stateTypes'
import MenuSelect from '../components/MenuSelect'
import RouteSelect from '../components/RouteSelect'
import PathSelect from '../components/PathSelect'
import IconSelect from '../components/IconSelect/index'
export default {
  name: 'MenuDetail',
  components: {
    MenuSelect,
    IconSelect,
    RouteSelect,
    PathSelect
  },
  props: {
    data: {
      default() {
        return {
          parentId: '',
          icon: '',
          code: '',
          title: '',
          remark: '',
          component: '',
          enable: true,
          meta: '',
          path: '',
          redirect: '',
          pathId: '',
          isAuth: false,
          operate: 'add'
        }
      }
    },
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      form: Object.assign({ enable: true, isAuth: false }, this.data),
      metas: [],
      meta: {
        key: '',
        value: ''
      },
      baseCode: '',
      metaIndex: -1,
      dialogVisible: false,
      show: this.visible,
      iconSelShow: false, //选图标弹窗
      configShow: false, //本地路由配置
      localConfig: '',
      loading: false,
      dataTree: {},
      type: '',
      activeMenu: '',
      config: [], //路由默认元数据选择
      query: [], //路由query参数配置
      params: [], //路由parmas参数配置
      showTag: [], //query参数展示
      showParams: [], //params参数展示
      key: '',
      value: '',
      paramsType: 'params',
      showed: false
    }
  },
  computed: {
    title() {
      switch (this.form.operate) {
        case 'add':
          return this.LANG.ADD
        case 'view':
          return this.LANG.VIEW
        default:
          return this.LANG.EDIT
      }
    },

    boolean() {
      return this.$store.state[ENUM].boolean || []
    },
    portal() {
      return this.$store.state.portal
    },
    routeTypes() {
      return this.$store.state.enum.routeTypes || []
    },
    metaConfig() {
      return this.$store.state.enum.metaConfig || []
    },
    paramsTypes() {
      let val = {}
      if (this.type != 'route') {
        val.disabled = true
        val.value = 'params'
      } else {
        val.value = 'params'
      }
      return [{ value: 'query' }, val]
    }
  },
  watch: {
    data() {
      this.form = Object.assign({ enable: true, isAuth: false }, this.data)
      this.metas = []
      let metas = {}
      if (this.form.meta) {
        metas = JSON.parse(this.form.meta)
        for (const [key, value] of Object.entries(metas)) {
          this.metas.push({
            key: key,
            value: value
          })
        }
      }
      if (!this.type && !metas.type) {
        this.type = 'route'
      }
      this.afterGet(metas)
    },
    visible() {
      this.show = this.visible
    }
  },
  mounted() {
    this.$nextTick(() => {
      let metas = {}
      if (this.form.meta) {
        metas = JSON.parse(this.form.meta)
        for (const [key, value] of Object.entries(metas)) {
          this.metas.push({
            key: key,
            value: value
          })
        }
      }
      this.afterGet(metas)
      if (!this.type && !metas.type) {
        this.type = 'route'
      }
    })
  },
  methods: {
    //显示或关闭菜单高级配置
    showconfig() {
      this.showed = !this.showed
    },
    //导入本地路由配置
    importLocal() {
      this.configShow = true
    },
    configCancel() {
      this.localConfig = ''
      this.configShow = false
    },
    //关闭选图标弹窗，param为false
    closeSelect(param) {
      this.iconSelShow = param
    },
    //获得图标,param为图标对象
    saveSelect(param) {
      this.form.icon = param.code
    },
    //菜单保存
    submit() {
      this.loading = true
      let form = JSON.parse(JSON.stringify(this.form))
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.beforeSubmit()
          const meta = {}
          if (this.metas.length) {
            this.metas.forEach((item) => {
              meta[item.key] = item.value
            })
          }
          form.meta = JSON.stringify(meta)
          let action = 'saveMenu'
          if (form.operate === 'add') {
            action = 'addMenu'
            form.type = this.$storage.get('auth_portal') || this.portal.type
          }
          Auth[action](form).then((res) => {
            if (res.status) {
              if (form.operate == 'add') {
                this.$message.success(this.LANG.ADD_SUCCESS)
              } else {
                this.$message.success(this.LANG.EDIT_SUCCESS)
              }
              this.form = {}
              this.showed = false
              // const data = JSON.parse(JSON.stringify(res.data))
              this.$parent.getMenuTree() // 更新树结构的数据
              this.close()
            }
          })
        }
        this.loading = false
      })
      this.loading = false
    },
    //关闭弹窗
    close() {
      this.$refs.form.resetFields()
      this.show = false
      this.showed = false
      //隐藏 路由本地配置
      this.configShow = false
      this.$emit('update:visible', this.show)
      //编辑弹窗关闭时 恢复菜单页树 的可收缩伸展
      this.$emit('reset', true)
      this.activeMenu = ''
      this.config = []
      this.query = []
      this.params = []
      this.showTag = []
    },
    //切换菜单类型
    change(val) {
      this.type = val
      this.paramsType = 'query'
      if (val != 'route' && this.showTag.length > 0) {
        this.showTag = this.showTag.filter((item) => {
          return item.type != 'info'
        })
      }
    },

    //保存菜单跳转参数
    doneParams() {
      let val = {},
        data = {
          key: this.key,
          value: this.value
        }

      if (this.paramsType == 'query') {
        val = {
          key: this.key,
          value: this.key + '=' + this.value,
          type: 'link'
        }
        this.query.push(data)
      } else {
        val = {
          key: this.key,
          value: this.key + ':' + this.value,
          type: 'info'
        }
        this.params.push(data)
      }
      this.showTag.push(val)
      this.key = ''
      this.value = ''
    },

    //
    handleEdit(val) {
      if (val.value.indexOf('=') != -1) {
        let index = this.query.findIndex(function (item) {
          return item.key == val.key
        })

        let value = val.value.split('=')[1]
        this.query[index].key = val.key
        this.query[index].value = value
      } else {
        let index = this.params.findIndex(function (item) {
          return item.key == val.key
        })
        let value = val.value.split(':')[1]
        this.params[index].key = val.key
        this.params[index].value = value
      }
    },
    //删除跳转参数tag
    handleClose(val) {
      if (val.value.indexOf('=') != -1) {
        let index = this.query.findIndex(function (item) {
          return item.key == val.key
        })
        this.query.splice(index, 1)
      } else {
        let index = this.params.findIndex(function (item) {
          return item.key == val.key
        })
        this.params.splice(index, 1)
      }
      this.showTag.splice(this.showTag.indexOf(val), 1)
    },
    //query或pramas的类型选择
    clear() {
      this.$set(this.form, 'icon', '')
    },
    changeType() {},
    clearType() {},
    //处理菜单meta数据
    beforeSubmit() {
      if (this.type) {
        this.metas.push({
          key: 'type',
          value: this.type
        })
      }
      if (this.activeMenu) {
        this.metas.push({
          key: 'activeMenu',
          value: this.activeMenu
        })
      } else {
        this.metas.push({
          key: 'activeMenu',
          value: ''
        })
      }
      if (this.config) {
        let config = []
        this.config.forEach((item) => {
          config.push(item)
        })
        this.metas.push({
          key: 'config',
          value: config
        })
      } else {
        this.metas.push({
          key: 'config',
          value: []
        })
      }
      if (this.type == 'route') {
        this.metas.push({
          key: 'query',
          value: this.query || []
        })
        this.metas.push({
          key: 'params',
          value: this.params || []
        })
      }

      if (this.type != 'route') {
        this.component = ''
      }
    },
    afterGet(metas) {
      if (metas.type) {
        this.type = metas.type
      }
      if (metas.activeMenu) {
        this.activeMenu = metas.activeMenu
      }
      if (metas.config) {
        metas.config.forEach((item) => {
          this.config.push(item)
        })
      }
      if (metas.query) {
        this.query = metas.query
        this.query.forEach((item) => {
          let val = {
            key: item.key,
            value: item.key + '=' + item.value,
            type: 'link'
          }
          this.showTag.push(val)
        })
      }
      if (metas.params) {
        this.params = metas.params
        this.params.forEach((item) => {
          let val = {
            key: item.key,
            value: item.key + ':' + item.value,
            type: 'info'
          }
          this.showTag.push(val)
        })
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.edit-input {
  .fks-input__inner,
  .fks-textarea__inner {
    border-width: 0;
    resize: none;
    background-color: #fff;

    &:hover {
      background-color: #f5f7fa;
    }

    &:focus {
      border-width: 1px;
      resize: vertical;
      background-color: #fff;

      + .fks-input__suffix {
        opacity: 1;
      }
    }
  }

  .fks-input__suffix {
    opacity: 0;
  }

  &:hover {
    .fks-cascader__label {
      border-radius: 4px;
      background-color: #f5f7fa;
    }
  }
}

.fawkes-form-item.is-error .edit-input {
  .fks-input__inner,
  .fks-textarea__inner {
    border-width: 1px;
    background-color: #fff;
  }
}

.show-suffix {
  .fks-input__suffix {
    opacity: 1;
  }
}

.except-input {
  padding: 0 15px;
}

.icon-input ::v-deep .fks-input__inner {
  cursor: pointer;
}

::v-deep .fks-dialog__body {
  padding-bottom: 0 !important;

  .meta-add {
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 8px;

    .fks-radio-group {
      width: 120px;
    }

    .fks-input {
      flex: 1;
    }
  }

  .meta-config {
    width: auto;
    height: auto;
    padding: 16px;
    margin-top: 16px;
    border: 1px solid #ddd;
    border-radius: 4px;
  }

  .meta-tag {
    margin-right: 8px;
    font-size: 15px;
  }
}
</style>